<?php

namespace App\Http\Controllers\Client;

use App\Exceptions\GeneralException;
use App\Models\Courier;
use App\Http\Controllers\Controller;
use App\Repositories\CourierRepository;
use App\Http\Requests\Client\Courier\CourierUpdate;
use App\Http\Requests\Client\Courier\ShowRequest;
use App\Repositories\UserLogRepository;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

class CourierController extends Controller
{

    protected $courierRepository;
    protected $userLogRepository;

    /**
     * CouriersController constructor.
     * @param CourierRepository $courierRepository
     * @param UserLogRepository $userLogRepository
     */
    public function __construct(
        CourierRepository $courierRepository,
        UserLogRepository $userLogRepository
    )
    {
        $this->courierRepository = $courierRepository;
        $this->userLogRepository = $userLogRepository;
    }

    /**
     * 获取快递员列表资源列表
     *
     * Date: 2018/05/24
     * @author Tenny
     * @param ShowRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function info(ShowRequest $request)
    {
        $courier_id = $request->get('courier_id', false);
        $couriers = $this->courierRepository->CourierInfo($courier_id);
        return success($couriers);
    }

    /**
     * 更新快递员资源
     *
     * Date: 2018/05/24
     * @author Tenny
     * @param CourierUpdate $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \App\Exceptions\GeneralException
     */
    public function update(CourierUpdate $request)
    {
        $user = Auth::user();
        $courier_id = $user->id;
        $service_id = $user->service_id;
        $name = $user->name;
        $ip = $request->getClientIp();
        $couriersAttr = $request->only([
            'phone',
            'name',
            'avatar',
        ]);
        DB::beginTransaction();
        try {
            Courier::where('id', $courier_id)->update($couriersAttr);
            DB::commit();
        } catch (\Illuminate\Database\QueryException $ex) {
            DB::rollback();
            throw new GeneralException('未知错误', 500);
        }
        //记录日志
        $operation = '更新了个人资料';
        $history = json_encode($user->toArray(), true);
        $actuality = json_encode($couriersAttr, true);
        $order_id = 0;//非订单
        $type = 1;//共派管理员
        $this->userLogRepository->myLog($courier_id, $service_id, $name, $operation, $history, $actuality, $order_id, $ip, $type);
        //删除个人资料缓存
        $redis_key = sprintf('COURIER_INFO_V1_%d', $courier_id);
        Redis::del($redis_key);
        $couriers = $this->courierRepository->CourierInfo($courier_id);
        return updated($couriers);
    }
}
